package com.yuncheng.spcyApi.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuncheng.spcyApi.alog.annotation.Log;
import com.yuncheng.spcyApi.bo.DbrBo;
import com.yuncheng.spcyApi.constant.jcy.JcydjbConstant;
import com.yuncheng.spcyApi.entity.*;
import com.yuncheng.entity.YcSysUser;
import com.yuncheng.spcyApi.service.ISysUserGzjlService;
import com.yuncheng.spcyApi.spcyService.ZdyUploadFileService;
import com.yuncheng.spcyApi.constant.common.LogConstant;
import com.yuncheng.spcyApi.constant.common.SpcyCommonConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.entity.SpcyUserBgsq;
import com.yuncheng.exception.BusinessException;
import com.yuncheng.spcyApi.service.ISpcyLogService;
import com.yuncheng.spcyApi.service.ISpcyUserBgsqService;
import com.yuncheng.spcyApi.service.IYcSysUserService;
import com.yuncheng.spcyApi.utils.DateConvert;
import com.yuncheng.spcyApi.utils.GetCurrentUserUtils;
import com.yuncheng.spcyApi.utils.GetUuIdUtils;
import com.yuncheng.spcyApi.utils.OrderItemUtils;
import com.yuncheng.vo.GetKsKz;
import com.yuncheng.spcyApi.vo.common.*;
import com.yuncheng.vo.CurrentUserVo;
import com.yuncheng.vo.HttpResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import utils.DateConversionUtils;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

@Api(tags = "用户信息变更申请-接口")
@RestController
@RequestMapping(value = "/api/spzx-spcy/userBgsq")
public class SpcyUserBgsqController {

    @Resource
    private IYcSysUserService sysUserService;

    @Resource
    private ISpcyUserBgsqService spcyUserBgsqService;

    @Resource
    private ISysUserGzjlService sysUserGzjlService;

    @Resource
    @Lazy
    private ZdyUploadFileService zdyUploadFileService;

    @Resource
    private ISpcyLogService spcyLogService;

    /** 查询审核人 */
    private DbrBo getBlr(){
        String dbrId = "";
        String dbr = "";

        List<GetKsKz> ksKzObjectList = sysUserService.getKsKzObject("", SpcyConstant.GW_DWBGSHR);
        if (CollectionUtil.isNotEmpty(ksKzObjectList)) {
            dbrId = ksKzObjectList.get(0).getId();
            dbr = ksKzObjectList.get(0).getRealname();
        }

        /*if (CollectionUtils.isNotEmpty(ksKzObjectList)) {
            for (GetKsKz ksKz : ksKzObjectList) {
                dbrId += ksKz.getId()+",";
                dbr += ksKz.getRealname()+",";
            }
        }*/
        return new DbrBo(dbrId, dbr);
    }

    /** 初始化-工作单位变更申请 */
    private SpcyUserBgsq initMyGzdwBgsq(){
        YcSysUser user = sysUserService.getById(GetCurrentUserUtils.getCurrentUserId());
        if (user == null) {
            throw new BusinessException("当前用户不存在！");
        }

        SpcyUserBgsq bgsq = new SpcyUserBgsq();
        bgsq.setId(GetUuIdUtils.ReplaceUuId());
        bgsq.setFuserid(user.getId());
        bgsq.setFbglx(SpcyCommonConstant.BGSQ_BGLX_GZDW);
        bgsq.setFshzt(SpcyCommonConstant.BGSQ_SHZT_ZC);
        bgsq.setUsername(user.getUsername());
        bgsq.setRealname(user.getRealname());
        bgsq.setFbgqxx(user.getFgzdw());

        // 获取审核人
        DbrBo blr = getBlr();
        bgsq.setFblrid(blr.getDbrId());
        bgsq.setFblr(blr.getDbr());

        spcyUserBgsqService.save(bgsq);

        return bgsq;
    }

    @Log(title = "查询工作单位变更审核-分页查询")
    @ApiOperation(value = "查询工作单位变更审核-分页查询")
    @GetMapping(value = "queryPageGzdwBgShList")
    public HttpResult queryPageGzdwBgShList(SpcyUserBgsq sq, String gjz, PageVo pageVo, OrderItemVo orderItemVo, StartEndStringVo timeVo){

        Page<SpcyUserBgsq> page = new Page<>(pageVo.getPageNo(), pageVo.getPageSize());
        LambdaQueryWrapper<SpcyUserBgsq> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(sq.getUsername()), SpcyUserBgsq::getUsername, sq.getUsername());
        queryWrapper.eq(StringUtils.isNotBlank(sq.getRealname()), SpcyUserBgsq::getRealname, sq.getRealname());
        queryWrapper.eq(SpcyUserBgsq::getFblrid, GetCurrentUserUtils.getCurrentUserId());

        if (StringUtils.isNotBlank(gjz)){
            queryWrapper
                    .and(f->f.like(SpcyUserBgsq::getRealname, gjz)
                            .or()
                            .like(SpcyUserBgsq::getFbgqxx, gjz)
                            .or()
                            .like(SpcyUserBgsq::getFbghxx, gjz)
                            .or()
                            .like(SpcyUserBgsq::getFsftybg, gjz)
                            .or()
                            .like(SpcyUserBgsq::getFshzt, gjz)
                    );
        }

        /*if (StringUtils.isBlank(sq.getFshzt())) {
            queryWrapper.eq(SpcyUserBgsq::getFshzt, SpcyCommonConstant.BGSQ_SHZT_WSH);
        }else if (sq.getFshzt().equals(SpcyCommonConstant.BGSQ_SHZT_YSH)){
            queryWrapper.eq(SpcyUserBgsq::getFshzt, SpcyCommonConstant.BGSQ_SHZT_YSH);
        }else if (sq.getFshzt().equals(SpcyCommonConstant.BGSQ_SHZT_WSH)){
            queryWrapper.eq(SpcyUserBgsq::getFshzt, SpcyCommonConstant.BGSQ_SHZT_WSH);
        }*/
        queryWrapper.eq(SpcyUserBgsq::getFbglx, SpcyCommonConstant.BGSQ_BGLX_GZDW);

        queryWrapper.ne(SpcyUserBgsq::getFshzt, SpcyCommonConstant.TXYPJP_SQ_SHZT_ZC);

       /* if (StringUtils.isNotBlank(timeVo.getStartTime()) && StringUtils.isBlank(timeVo.getEndTime())){
            queryWrapper.apply("ffqsj >= {0}",timeVo.getStartTime());
        }else if (StringUtils.isBlank(timeVo.getStartTime()) && StringUtils.isNotBlank(timeVo.getEndTime())){
            queryWrapper.apply("ffqsj <= {0}", timeVo.getEndTime());
        }else if (StringUtils.isNotBlank(timeVo.getStartTime()) && StringUtils.isNotBlank(timeVo.getEndTime())){
            queryWrapper.apply("ffqsj >= {0} and ffqsj <= {1}",timeVo.getStartTime(), timeVo.getEndTime());
        }*/

        if (StringUtils.isBlank(orderItemVo.getOrderItem())) {
            queryWrapper.orderByDesc(SpcyUserBgsq::getFfqsj);
        }else {
            OrderItemUtils.setOrderItem(queryWrapper, orderItemVo);
        }
        IPage<SpcyUserBgsq> pageList = spcyUserBgsqService.page(page, queryWrapper);

        return HttpResult.ok(pageList);
    }

    @Log(title = "个人历史单位变更-分页查询")
    @ApiOperation(value = "个人历史单位变更-分页查询")
    @GetMapping(value = "queryMyGzdwSqList")
    public HttpResult queryMyGzdwSqList(String gjz, PageVo pageVo, OrderItemVo orderItemVo){

        return HttpResult.ok(spcyUserBgsqService.selectMyLsbgdwPageList(gjz, pageVo, orderItemVo));
    }

    @Log(title = "查询我的暂存申请")
    @ApiOperation(value = "查询我的暂存申请")
    @GetMapping(value = "queryBgsqInfo")
    public HttpResult queryBgsqInfo(){

        SpcyUserBgsq sq = null;

        List<SpcyUserBgsq> wshList = spcyUserBgsqService.selectMyGzdwBgsqInWsh(GetCurrentUserUtils.getCurrentUserId());
        if (CollectionUtil.isEmpty(wshList)){
            sq = initMyGzdwBgsq();
        }else {
            sq = wshList.get(0);

            if (StringUtils.isNotBlank(sq.getFshzt()) && sq.getFshzt().equals(SpcyCommonConstant.BGSQ_SHZT_ZC)){
                sq.setFfqsj(new Date());
                spcyUserBgsqService.updateById(sq);
            }

        }

        Map resultMap = new HashMap<>();
        resultMap.put("sq", sq);
        return HttpResult.ok(resultMap);
    }

    @Log(title = "保存申请-暂存")
    @ApiOperation(value = "保存申请-暂存")
    @PostMapping(value = "saveBgsqInGzdw")
    public HttpResult saveBgsqInGzdw(@RequestBody SpcyUserBgsq sq) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        if (StringUtils.isBlank(sq.getId())){
            throw new BusinessException("参数为空！");
        }

        SpcyUserBgsq updateSq = spcyUserBgsqService.getById(sq.getId());
        if (updateSq == null){
            throw new BusinessException("没有相匹配的数据！");
        }

        if (StringUtils.isBlank(updateSq.getFbghxx())){
            updateSq.setFbghxx(sq.getFbghxx());
        }else if (StringUtils.isNotBlank(sq.getFbghxx()) && !updateSq.getFbghxx().equals(sq.getFbghxx())){
            updateSq.setFbghxx(sq.getFbghxx());
        }

        ConvertUtils.register(new DateConvert(), java.util.Date.class);
        // 自动完成页面到bean的数据对接
        BeanUtils.populate(updateSq, BeanUtils.describe(sq));

        updateSq.setUpdateTime(new Date());
        spcyUserBgsqService.updateById(updateSq);

        return HttpResultVo.HttpResultSave(updateSq, "保存成功");
    }

    @Log(title = "提交申请")
    @ApiOperation(value = "提交申请")
    @PostMapping(value = "submitBgsqInGzdw")
    public HttpResult submitBgsqInGzdw(@RequestBody SpcyUserBgsq sq) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        if (StringUtils.isBlank(sq.getId())){
            throw new BusinessException("参数为空！");
        }

        SpcyUserBgsq updateSq = spcyUserBgsqService.getById(sq.getId());
        if (updateSq == null){
            throw new BusinessException("没有相匹配的数据！");
        }

        if (StringUtils.isNotBlank(updateSq.getFshzt()) && !updateSq.getFshzt().equals(SpcyCommonConstant.BGSQ_SHZT_ZC)){
            throw new BusinessException("已经提交，无法重复提交！");
        }

        if (StringUtils.isBlank(updateSq.getFbghxx())){
            if (StringUtils.isBlank(sq.getFbghxx())){
                throw new BusinessException("请输入新的工作单位！");
            }
            updateSq.setFbghxx(sq.getFbghxx());
        }else if (StringUtils.isNotBlank(sq.getFbghxx()) && !sq.getFbghxx().equals(updateSq.getFbghxx())){
            updateSq.setFbghxx(sq.getFbghxx());
        }

        ConvertUtils.register(new DateConvert(), java.util.Date.class);
        // 自动完成页面到bean的数据对接
        BeanUtils.populate(updateSq, BeanUtils.describe(sq));

        updateSq.setFfqsj(new Date());
        updateSq.setUpdateTime(new Date());
        updateSq.setFshzt(SpcyCommonConstant.BGSQ_SHZT_WSH);
        spcyUserBgsqService.updateById(updateSq);

        return HttpResult.ok("提交成功");
    }

    @Log(title = "提交审核")
    @ApiOperation(value = "提交审核")
    @PostMapping(value = "submitShInBgGzdw")
    public HttpResult submitShInBgGzdw(@RequestBody SqInBggzdwVo submitVo){
        CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();
        if (currentUser == null){
            throw new BusinessException("当前登录已失效，请重新登录！");
        }

        if (StringUtils.isBlank(submitVo.getId())){
            throw new BusinessException("参数为空！");
        }

        if (StringUtils.isBlank(submitVo.getSfty())){
            throw new BusinessException("是否同意参数为空！");
        }

        SpcyUserBgsq bgsq = spcyUserBgsqService.getById(submitVo.getId());
        if (bgsq == null) {
            throw new BusinessException("没有相匹配的数据！");
        }

        if (StringUtils.isNotBlank(bgsq.getFshzt()) && bgsq.getFshzt().equals(SpcyCommonConstant.BGSQ_SHZT_YSH)){
            throw new BusinessException("已经提交，无法重复提交！");
        }

        if (submitVo.getSfty().equals("是") || submitVo.getSfty().equals("true")){
            bgsq.setFsftybg(SpcyCommonConstant.BGSQ_SFTYBG_YES);
        }else {
            bgsq.setFsftybg(SpcyCommonConstant.BGSQ_SFTYBG_NO);
        }

        bgsq.setFblyj(submitVo.getOpinion());
        bgsq.setFblsj(new Date());
        bgsq.setFshzt(SpcyCommonConstant.BGSQ_SHZT_YSH);
        spcyUserBgsqService.updateById(bgsq);

        /** 审核通过 */
        YcSysUser bgUser = sysUserService.getById(bgsq.getFuserid());
        if (bgUser != null && bgsq.getFbglx().equals(SpcyCommonConstant.BGSQ_BGLX_GZDW)
                && bgsq.getFsftybg().equals(SpcyCommonConstant.BGSQ_SFTYBG_YES)){

            // 变更日志
            String addSysUserOper = "变更工作单位：变更前["+bgUser.getFgzdw()+"]; 变更后["+bgsq.getFbghxx()+"]";
            addSysUserOper += "变更单位地址：变更前["+bgUser.getFgzdwdz()+"]; 变更后["+bgsq.getFxdwdz()+"]";
            addSysUserOper += "变更单位部门：变更前["+bgUser.getFgzdwbm()+"]; 变更后["+bgsq.getFxdwbm()+"]";

            addSysUserOper += "变更单位职务：变更前["+bgUser.getFzw()+"]; 变更后["+bgsq.getFxdwzw()+"]";
            addSysUserOper += "变更单位岗位：变更前["+bgUser.getFcsgz()+"]; 变更后["+bgsq.getFxdwgw()+"]";

            addSysUserOper += "变更工作开始时间：变更前["+bgUser.getFgzkssj()+"]; 变更后["+bgsq.getFxdwdrsj()+"]";
            addSysUserOper += "变更工作结束时间：变更前["+bgUser.getFgzjssj()+"]; 变更后["+JcydjbConstant.GZJL_END_TIME_ZJ+"]";


            bgUser.setFgzdw(bgsq.getFbghxx());
            bgUser.setFgzdwbm(bgsq.getFxdwbm());
            bgUser.setFgzdwdz(bgsq.getFxdwdz());

            bgUser.setFzw(bgsq.getFxdwzw());
            bgUser.setFcsgz(bgsq.getFxdwgw());

            bgUser.setFgzkssj(bgsq.getFxdwdrsj());
            bgUser.setFgzjssj(JcydjbConstant.GZJL_END_TIME_ZJ);

            bgUser.setFdwlx(bgsq.getFxdwlx());
            bgUser.setFssqy(bgsq.getFxdwszds());

            if (StringUtils.isNotBlank(bgsq.getFxdwlx()) && bgsq.getFxdwlx().contains(SpcyConstant.USER_DWLX)) {
                bgUser.setFsfyjsry(SpcyConstant.HCY_SFYJSRY_YES);
            }else {
                bgUser.setFsfyjsry(SpcyConstant.HCY_SFYJSRY_NO);
            }

            sysUserService.updateById(bgUser);


            SysUserGzjl newGzjl = new SysUserGzjl();
            newGzjl.setId(GetUuIdUtils.ReplaceUuId());

            newGzjl.setFuserid(bgUser.getId());
            newGzjl.setFusermc(bgUser.getRealname());
            newGzjl.setFgzdw(bgUser.getFgzdw());
            newGzjl.setFcsgz(bgUser.getFcsgz());

            newGzjl.setFzw(bgUser.getFzw());
            newGzjl.setFzc(bgUser.getFzc());
            newGzjl.setFgzbm(bgUser.getFgzdwbm());

            newGzjl.setFgzkssj(bgUser.getFgzkssj());
            newGzjl.setFgzjssj(bgUser.getFgzjssj());
            sysUserGzjlService.save(newGzjl);

            /** 修改工作经历最新的值 */
            if (StringUtils.isNotBlank(bgsq.getFbgqxx())) {
                List<SysUserGzjl> oldGzjlList = sysUserGzjlService.list(new LambdaQueryWrapper<SysUserGzjl>()
                        .eq(SysUserGzjl::getFgzdw, bgsq.getFbgqxx())
                        .orderByDesc(SysUserGzjl::getCreateTime));
                if (CollectionUtil.isNotEmpty(oldGzjlList)){
                    SysUserGzjl gzjl = oldGzjlList.get(0);
                    gzjl.setFgzjssj(bgsq.getFxdwdrsj());
                    sysUserGzjlService.updateById(gzjl);
                }
            }

            spcyLogService.addLogs(LogConstant.LOGS_JCYGL,addSysUserOper,bgsq.getFuserid(),"变更工作单位审核通过",SpcyConstant.LOGS_SYS_TYPE_TJ);
        }

        return HttpResult.ok("提交成功");
    }

    @Log(title = "查询当前申请信息")
    @ApiOperation(value = "查询当前申请信息")
    @GetMapping(value = "querySqInfo")
    public HttpResult querySqInfo(@RequestParam(value = "id",defaultValue = "")String id){
        if (StringUtils.isBlank(id)){
            throw new BusinessException("参数为空！");
        }
        SpcyUserBgsq sq = spcyUserBgsqService.getById(id);
        if (sq == null){
            throw new BusinessException("没有相匹配的数据！");
        }
        return HttpResult.ok(sq);
    }

    @Log(title = "上传文件-变更文件")
    @ApiOperation(value = "上传文件-变更文件")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "file",value = "文件不能为空",required = true),
            @ApiImplicitParam(name = "id",value = "申请id",required = true)
    })
    @PostMapping(value = "/uploadFile")
    public HttpResult<?> uploadFile(@RequestPart("file") MultipartFile[] uploadFile,
                                        @RequestParam(value = "id",defaultValue = "") String id){
        if (StringUtils.isBlank(id)){
            throw new BusinessException("上传失败，申请参数为空！");
        }
        SpcyUserBgsq bgsq = spcyUserBgsqService.getById(id);
        if (bgsq == null){
            throw new BusinessException("没有相匹配的数据！");
        }

        List<SpcySqsxWjjl> wjjlList = zdyUploadFileService.queryWjjlByPid(id);
        if (CollectionUtil.isNotEmpty(wjjlList)){
            for (SpcySqsxWjjl wjjl : wjjlList) {
                zdyUploadFileService.deleteFileRecords(wjjl);
                zdyUploadFileService.deleteFileByUrl(wjjl.getFcflj());
            }
        }

        String wjid = GetUuIdUtils.ReplaceUuId();
        zdyUploadFileService.uploadFile(uploadFile, id, LogConstant.LOGS_USER_BGSQ, SpcyConstant.USER_BGSQ_WJJL_FILE_BASE_URL+"/"+ DateConversionUtils.DateToYear(new Date()), wjid);

        String wjHttpUrl = zdyUploadFileService.genWjllHttpUrl(wjid);
        bgsq.setFfjdz(wjHttpUrl);
        spcyUserBgsqService.updateById(bgsq);

        return HttpResultVo.HttpResultSave(bgsq,"上传成功");
    }

}
